package com.example.mymvvmdemo.models.user_info;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.View;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.Constants;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivityUserInfoBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.dialog.PromptInputDialog;
import com.example.mymvvmdemo.entity.FailEntity;
import com.example.mymvvmdemo.models.add_article.entity.AddArticleEntity;
import com.example.mymvvmdemo.models.bind_email.BindEmailViewModel;
import com.example.mymvvmdemo.models.main.fragment.mine.entity.UserInfoEntity;
import com.example.mymvvmdemo.net.presenter.GetPresenter;
import com.example.mymvvmdemo.net.presenter.ImagePresenter;
import com.example.mymvvmdemo.net.presenter.PutBodyPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.FileUtils;
import com.example.mymvvmdemo.utils.GlideUtils;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.io.File;
import java.util.HashMap;

public class UserInfoActivity extends BaseLoadActivity<ActivityUserInfoBinding> implements View.OnClickListener, IView.GetView, IView.ImageView, IView.PutBodyView {

    public static void startUserInfoActivity(Activity activity) {
        Intent intent = new Intent(activity, UserInfoActivity.class);
        activity.startActivity(intent);
    }

    public UserInfoViewModel viewModel;
    private GetPresenter getPresenter;
    private ImagePresenter imagePresenter;
    private PutBodyPresenter putBodyPresenter;
    private PromptInputDialog nickNameDialog;
    private PromptInputDialog bioDialog;
    private PromptInputDialog birthdayDialog;
    private PromptInputDialog locationDialog;
    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;


    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }

    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(UserInfoViewModel.class);
        getPresenter = new GetPresenter(this);
        imagePresenter = new ImagePresenter(this);
        putBodyPresenter = new PutBodyPresenter(this);
        initTitle(getString(R.string.user_info));
        registerPermissionLauncher();
        registerGalleryLauncher();
    }

    @Override
    protected void initListener() {
        binding.include.ivBack.setOnClickListener(this);
        binding.ivHead.setOnClickListener(this);
        binding.tvNickname.setOnClickListener(this);
        binding.clPhone.setOnClickListener(this);
        binding.clEmail.setOnClickListener(this);
        binding.clBirthday.setOnClickListener(this);
        binding.clLocation.setOnClickListener(this);
        binding.clBio.setOnClickListener(this);
        binding.clChangePassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_head:
                //选择图片
                checkPermissionAndOpenGallery();
                break;
            case R.id.tv_nickname:
                if (nickNameDialog != null) {
                    nickNameDialog.show();
                }
                break;
            case R.id.cl_bio:
                if (bioDialog != null) {
                    bioDialog.show();
                }
                break;
            case R.id.cl_phone:
                viewModel.startBindEmailActivity(this, BindEmailViewModel.TYPE_PHONE);
                break;
            case R.id.cl_email:
                viewModel.startBindEmailActivity(this, BindEmailViewModel.TYPE_EMAIL);
                break;
            case R.id.cl_birthday:
                if (birthdayDialog != null) {
                    birthdayDialog.show();
                }
                break;
            case R.id.cl_location:
                if (locationDialog != null) {
                    locationDialog.show();
                }
                break;
            case R.id.cl_change_password:
                viewModel.startChangePassWordActivity(this);
                break;
            default:
                break;
        }
    }

    @Override
    public void initDialog() {
        super.initDialog();

        nickNameDialog = new PromptInputDialog(this);
        nickNameDialog.setInputText(R.string.input_nick_name);
        nickNameDialog.setListener(new PromptInputDialog.PromptClickListener() {
            @Override
            public void onCancelClick() {

            }

            @Override
            public void onConfirmClick(String input) {
                viewModel.nickname = input;
                startLoadUpdateUserInfo();
            }
        });

        bioDialog = new PromptInputDialog(this);
        bioDialog.setInputText(R.string.input_bio);
        bioDialog.setListener(new PromptInputDialog.PromptClickListener() {
            @Override
            public void onCancelClick() {

            }

            @Override
            public void onConfirmClick(String input) {
                viewModel.bio = input;
                startLoadUpdateUserInfo();
            }
        });

        birthdayDialog = new PromptInputDialog(this);
        birthdayDialog.setInputText(R.string.input_birthday);
        birthdayDialog.setListener(new PromptInputDialog.PromptClickListener() {
            @Override
            public void onCancelClick() {

            }

            @Override
            public void onConfirmClick(String input) {
                viewModel.birthday = input;
                startLoadUpdateUserInfo();
            }
        });

        locationDialog = new PromptInputDialog(this);
        locationDialog.setInputText(R.string.input_location);
        locationDialog.setListener(new PromptInputDialog.PromptClickListener() {
            @Override
            public void onCancelClick() {

            }

            @Override
            public void onConfirmClick(String input) {
                viewModel.location = input;
                startLoadUpdateUserInfo();
            }
        });

    }

    /***********************************自定义方法**************************************/
    public void initTitle(String title) {
        binding.include.tvTitle.setVisibility(View.VISIBLE);
        binding.include.tvTitle.setText(title);
    }

    public void startLoadUpdateUserInfo() {

        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        if (!StrUtils.isEmpty(viewModel.nickname)) {
            hashMap.put("nickname", viewModel.nickname);
        }
        if (!StrUtils.isEmpty(viewModel.bio)) {
            hashMap.put("bio", viewModel.bio);
        }
        if (!StrUtils.isEmpty(viewModel.location)) {
            hashMap.put("location", viewModel.location);
        }
        if (!StrUtils.isEmpty(viewModel.birthday)) {
            hashMap.put("birthday", viewModel.birthday);
        }
        putBodyPresenter.startLoadPutBody(UrlConstants.updateUserInfo, hashMap, UrlTypeConstants.updateUserInfo);

    }

    public void startLoadUserInfo() {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        getPresenter.startLoadGet(UrlConstants.userInfo, hashMap, UrlTypeConstants.userInfo);
    }

    private void registerPermissionLauncher() {
        viewModel.requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
            if (isGranted) {
                openGallery();
            } else {
                toast("需要存储权限才能选择图片", ToastUtils.TOA_W);
            }
        });
    }

    private void registerGalleryLauncher() {
        viewModel.galleryLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Uri selectedImageUri = result.getData().getData();
                if (selectedImageUri != null) {
                    handleSelectedImage(selectedImageUri);
                }
            }
        });
    }

    private void handleSelectedImage(Uri imageUri) {

        // Convert Uri to File
        File imageFile = FileUtils.getFileByUri(this, imageUri);
        if (imageFile != null) {
            viewModel.fileUrl = imageFile.getPath();
        }

        if (imageFile == null) {
            return;
        }

        if (fileIsBig(imageFile)) {
            toast(R.string.file_big, ToastUtils.TOA_W);
            return;
        }

        GlideUtils.loadRoundImage(this, viewModel.fileUrl, R.mipmap.app_icon, binding.ivHead);
        startLoadUploadHead();

    }

    public boolean fileIsBig(File file) {
        long fileSizeInBytes = file.length();
        long fileSizeInMb = fileSizeInBytes / (1024 * 1024);

        LogUtils.d("文件大小: " + fileSizeInMb + " MB");
        // 判断文件大小是否超过1MB
        if (fileSizeInBytes > 1024 * 1024) { // 1MB in bytes
            return true;
        } else {
            return false;
        }
    }

    public void startLoadUploadHead() {
        HashMap<String, String> hashMap = new HashMap<>();
        imagePresenter.startLoadImage(UrlConstants.uploadHead, hashMap, new File(viewModel.fileUrl), "avatar", UrlTypeConstants.uploadHead);
    }


    private void checkPermissionAndOpenGallery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // For Android 13+, check READ_MEDIA_IMAGES
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                viewModel.requestPermissionLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES);
            } else {
                openGallery();
            }
        } else {
            // For Android 6-12, check READ_EXTERNAL_STORAGE
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                viewModel.requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
            } else {
                openGallery();
            }
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        viewModel.galleryLauncher.launch(intent);
    }

    /****************************************数据请求回调***************************************/
    @Override
    public void loadGetSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.userInfo)) {
            loadUserInfoSuccess(result, code);
        }
    }

    @Override
    public void loadGetFail(String message, String type) {
        if (type.equals(UrlTypeConstants.userInfo)) {
            loadUserInfoFail();
        }
    }

    @Override
    public void loadGetAccountError(int code) {

    }

    @Override
    public void loadGetNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    @Override
    public void loadImageSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.uploadHead)) {
            loadUserHeadSuccess(result, code);
        }
    }

    @Override
    public void loadImageFail(String message, String type) {
        if (type.equals(UrlTypeConstants.uploadHead)) {
            loadUserHeadFail();
        }
    }

    @Override
    public void loadImageAccountError(int code) {

    }

    @Override
    public void loadImageNetWorkError(String type) {
        dismissDialog();
        toast(R.string.user_info_upload_head_fail, ToastUtils.TOA_W);
    }

    @Override
    public void loadPutBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.updateUserInfo)) {
            loadUpdateUserInfoSuccess(result, code);
        }
    }

    @Override
    public void loadPutBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.updateUserInfo)) {
            loadUpdateUserInfoFail();
        }
    }

    @Override
    public void loadPutBodyAccountError(int code) {

    }

    @Override
    public void loadPutBodyNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    /****************************************处理请求后数据***************************************/
    private void loadUserHeadSuccess(String result, int code) {
        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        toast(R.string.user_info_upload_head_success, ToastUtils.TOA_S);
    }

    private void loadUserHeadFail() {
        dismissDialog();
        toast(R.string.user_info_upload_head_fail, ToastUtils.TOA_W);
    }

    public void loadUserInfoSuccess(String result, int code) {

        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        try {
            UserInfoEntity userInfoEntity = gson.fromJson(result, UserInfoEntity.class);
            UserInfoEntity.DataDTO.UserDTO user = userInfoEntity.getData().getUser();

            String avatar = user.getAvatar();
            String nickname = user.getNickname();
            String phone = user.getMobile();
            String email = user.getEmail();
            String birthday = user.getBirthday();
            String bio = user.getBio();
            String location = user.getLocation();
            String website = user.getWebsite();
            if (!StrUtils.isEmpty(website)) {
                viewModel.website = website;
            }

            if (!StrUtils.isEmpty(avatar)) {
                GlideUtils.loadRoundImage(this, Constants.URL_CHINA_SC + avatar, R.drawable.ic_svg_user, binding.ivHead);
            }
            if (!StrUtils.isEmpty(nickname)) {
                viewModel.nickname = nickname;
                binding.tvNickname.setText(nickname);
            }
            if (!StrUtils.isEmpty(phone)) {
                binding.tvPhone.setText(phone);
            }
            if (!StrUtils.isEmpty(email)) {
                binding.tvEmail.setText(email);
            }
            if (!StrUtils.isEmpty(birthday)) {
                viewModel.birthday = birthday;
                binding.tvBirthday.setText(birthday);
            }
            if (!StrUtils.isEmpty(bio)) {
                viewModel.bio = bio;
                binding.tvBio.setText(bio);
            }
            if (!StrUtils.isEmpty(location)) {
                viewModel.location = location;
                binding.tvLocation.setText(location);
            }

        } catch (Exception e) {
            loadUserInfoFail();
        }

    }

    private void loadUserInfoFail() {
        dismissDialog();
    }

    private void loadUpdateUserInfoSuccess(String result, int code) {
        loadUpdateUserInfoCom();
        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        try {
//            UserInfoEntity userInfoEntity = gson.fromJson(result, UserInfoEntity.class);
            toast(R.string.success, ToastUtils.TOA_S);
            startLoadUserInfo();
        } catch (Exception e) {
            loadUserInfoFail();
        }

    }

    private void loadUpdateUserInfoFail() {
        dismissDialog();
        loadUpdateUserInfoCom();
        toast(R.string.fail, ToastUtils.TOA_F);
    }

    private void loadUpdateUserInfoCom() {
        viewModel.nickname = null;
        viewModel.bio = null;
        viewModel.location = null;
        viewModel.birthday = null;
    }

    /**************************************生命周期*********************************************/
    @Override
    protected void onResume() {
        super.onResume();
        startLoadUserInfo();
    }


}